package com.rchat.pocmini.activity.fragment.groups;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;

import com.airtalkee.sdk.entity.AirSession;
import com.aso.common.dialog.AlertDialogCustomConfirm;
import com.aso.common.dialog.CustomDialog;
import com.aso.common.utils.AppUtils;
import com.itsdf07.alog.ALog;
import com.rchat.pocmini.R;
import com.rchat.pocmini.account.PocAccount;
import com.rchat.pocmini.activity.bean.GroupBean;
import com.rchat.pocmini.activity.bluetoothwalkie.WalkieChannelMvpActivity;
import com.rchat.pocmini.activity.changenickname.ChangeNicknameMvpActivity;
import com.rchat.pocmini.activity.chat.ChatMvpActivity;
import com.rchat.pocmini.activity.creategroup.CreateGroupMvpActivity;
import com.rchat.pocmini.activity.debug.DebugActivity;
import com.rchat.pocmini.activity.fragment.GroupsAdapter;
import com.rchat.pocmini.activity.groupsselect.GroupsSelectorActivity;
import com.rchat.pocmini.activity.groupsselect.view.GroupSelectBean;
import com.rchat.pocmini.activity.recharge.ReChargeMvpActivity;
import com.rchat.pocmini.activity.searchgroup.SearchGroupMvpActivity;
import com.rchat.pocmini.activity.setting.SettingActivity;
import com.rchat.pocmini.activity.view.ClearEditText;
import com.rchat.pocmini.bean2eventbus.EventBusAccountBean;
import com.rchat.pocmini.bean2eventbus.EventBusRemoteBean;
import com.rchat.pocmini.bean2eventbus.UpdateGroupBean;
import com.rchat.pocmini.common.mvp.BaseMvpFragment;
import com.rchat.pocmini.global.AppGlobal;
import com.rchat.pocmini.global.IntentKeyGlobal;
import com.rchat.pocmini.service.PocService;
import com.rchat.pocmini.service.RchatClientService;
import com.rchat.pocmini.util.SPUtil;
import com.umeng.analytics.MobclickAgent;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by itsdf07 on 2017/8/24.
 */

public class GroupsFragment extends BaseMvpFragment<GroupsPresenterImpl, GroupsModelImpl>
        implements GroupsContract.View,
        GroupsAdapter.ItemTouchHelperAdapterCallback {
    /**
     * 添加群组控件
     */
    @BindView(R.id.layout_create_group)
    View mLayoutCreateGroup;
    /**
     * 搜索群组控件
     */
    @BindView(R.id.layout_search_group)
    View mLayoutSearch;
    @BindView(R.id.layout_avatar)
    View mLayoutAvatar;
    @BindView(R.id.tv_empty)
    View mEmptyView;
    /**
     * 群组ListView
     */
    @BindView(R.id.container_groups)
    RecyclerView mGroupsRecyclerView;
    private GroupsAdapter mAdapter;

    private TextView mTvNickName;
    private TextView mTvExpireData;

    @Override
    public void initPresenter() {
        mPresenter.setVM(this, mModel);
    }

    @Override
    public int getLayoutId() {
        return R.layout.fragment_groups;
    }

    @Override
    public void initView() {
        mGroupsRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
    }

    @Override
    public void doAfterInitView() {
    }


    @OnClick({R.id.layout_create_group,
            R.id.layout_search_group,
            R.id.layout_avatar})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.layout_create_group:
                startActivity(new Intent(getContext(), CreateGroupMvpActivity.class));
                break;
            case R.id.layout_search_group:
                startActivity(new Intent(getContext(), SearchGroupMvpActivity.class));
                break;
            case R.id.layout_avatar:
                //展示个人信息dialog
                showAccountInfoDialog();
                //蓝牙功能，账号续费等等在这写
                break;
        }
    }

    @Override
    public void updateList(ArrayList<GroupBean> data) {
        //PS:由于在P的初始化比initView早，而在P的onPStart中有调用这个，所以这边使用到的内容在onPStart后面初始化的都需要判空
        if (mAdapter == null) {
            mAdapter = new GroupsAdapter(data, this);
            mGroupsRecyclerView.setAdapter(mAdapter);
        } else {
            mAdapter.setData(data);
        }
        if (mEmptyView != null) {
            mEmptyView.setVisibility(data.size() > 0 ? View.GONE : View.VISIBLE);
        }

        if (!mPresenter.checkVipStatus(mPresenter.getGroupsCreateData().size())) {
            unVipTip();
        }
    }

    @Override
    public void updateListenChannel(ArrayList<GroupBean> data) {

    }

    @Override
    public void updateExpireData(String expireData) {
        if (mTvExpireData != null) {
            mTvExpireData.setText(expireData);
        }
    }

    @Override
    public void updateNickName(String nickName) {
        if (mTvNickName != null) {
            mTvNickName.setText(nickName);
        }
    }

    @Override
    public void unVipTip() {
        CustomDialog.Builder builder = new CustomDialog.Builder(getContext());
        builder.setMessage(getString(R.string.text_unvip));
        builder.setTitle(getString(R.string.tip_unvip));
        builder.setCancelable(false);
        builder.setInterceptBack(true);
        builder.setPositiveButton(getString(R.string.text_recharge), new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                Intent intent = new Intent(mActivity, ReChargeMvpActivity.class);
                intent.putExtra(IntentKeyGlobal.IntentRecharge.INTENT_KEY_FROM, IntentKeyGlobal.IntentRecharge.INTENT_VALUE_VIPCHECK);
                mActivity.startActivity(intent);
            }
        });

        builder.setNegativeButton(getString(R.string.text_select_list),
                new android.content.DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        Intent intent = new Intent(mActivity, GroupsSelectorActivity.class);
                        intent.putExtra(AppGlobal.KeyIntent.KEY_INTENT_UPDATE_GROUPS_BACK, true);
                        mActivity.startActivity(intent);
                    }
                });

        builder.create().show();
    }

    @Override
    public AirSession onItemChannelListened(GroupBean bean) {
        ALog.d("groupId = %s", bean.getGroupId());
        mPresenter.setChannelListened(bean);
        return null;
    }

    @Override
    public void onItemChannelLocked(GroupBean bean) {
        mPresenter.setChannelLocked(bean);
    }

    @Override
    public void onItemClick(View view, GroupBean bean) {
        ALog.d("groupName = %s", bean.getGroupName());
        /**
         * @author sudf
         * @data 2017.8.25
         * 为了统一使用onItemChannelLocked(bean)接口使用了一个偷懒小技巧，这边把锁的状态统一改为未上锁，
         * 然后在onItemChannelLocked(bean)接口中才会执行上锁状态
         */
        bean.setIsLocked(false);
        onItemChannelLocked(bean);

        if (mPresenter.getChannelListeningList().size() >= mPresenter.SESSION_MAX_COUNT
                && !bean.isListen()) {
            return;
        }
        Intent intent = new Intent();
        intent.setClass(mActivity, ChatMvpActivity.class);
        intent.putExtra(GroupsPresenterImpl.KEY_GROUPID, bean.getGroupId());
        intent.putExtra("groupName", bean.getGroupName());
        mActivity.startActivity(intent);
    }

    @Override
    public void onItemLongClick(View view, GroupBean bean, int position) {
        for (GroupSelectBean groupSelectBean : mPresenter.getGroupsCreateData()) {
            if (groupSelectBean == null || bean == null) {
                return;
            }
            if (groupSelectBean.getGroupId().equals(bean.getGroupId())) {
                modifyGroupName(bean);
                return;
            }
        }
        showShortToast("您不是群主，不能修改群组名称");

    }

    /**
     * 删除监听列表中的某一个群组并重新获取群组列表
     *
     * @param groupId
     */
    public void doDeleteGroup(String groupId) {
        if (!TextUtils.isEmpty(groupId)) {
            for (int i = 0; i < mPresenter.getChannelListeningList().size(); i++) {
                GroupBean bean = mPresenter.getChannelListeningList().get(i);
                if (bean.getGroupId().equals(groupId)) {
                    mPresenter.getChannelListeningList().remove(bean);
                    break;
                }
            }
        } else {
            mPresenter.setAirtalkeeChannel();
        }

        UpdateGroupBean bean = new UpdateGroupBean();
        bean.setCurrentEvent(UpdateGroupBean.EVENT_GROPULIST_UPDATE);
        bean.setTarget(this.getClass(), GroupsPresenterImpl.class, "onEventBusUpdateGroups");
        mPresenter.onEventBusUpdateGroups(bean);
    }


    /**
     * 修改群组昵称对话框
     */
    private void modifyGroupName(final GroupBean bean) {
        CustomDialog.Builder builder = new CustomDialog.Builder(getContext());
        final ClearEditText view = (ClearEditText) LayoutInflater.from(getContext()).inflate(R.layout.layout_modify_nickname, null);
        builder.setContentView(view);
        builder.setTitle("当前群组名:" + bean.getGroupName());
        builder.setPositiveButton(getContext().getString(R.string.confirm), new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                if (TextUtils.isEmpty(view.getText().toString())) {
                    showShortToast(R.string.group_name_null_error);
                    return;
                }
                if (view.getText().toString().length() > 10) {
                    showShortToast(R.string.group_name_more_than_ten_error);
                    return;
                }
                dialog.dismiss();
                AlertDialogCustomConfirm.Builder builder = new AlertDialogCustomConfirm.Builder(mActivity);
                builder.setContent("确定修改为：" + view.getText().toString())
                        .setPositiveButton(new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                                mPresenter.modifyGroupName(bean.getGroupId(), view.getText().toString());
                            }
                        })
                        .setNegativeButton(new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        }).create().show();
            }
        });

        builder.setNegativeButton(getContext().getString(R.string.cancle),
                new android.content.DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });

        builder.create().show();
    }

    private void showAccountInfoDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
        final LayoutInflater inflater = getActivity().getLayoutInflater();
        final View layout = inflater.inflate(R.layout.account_info_dialog_layout, null);//获取自定义布局 
        //  
        mTvExpireData = (TextView) layout.findViewById(R.id.tv_expire_date);
        mTvExpireData.setText(PocAccount.getExpireDate());
        View rl1 = layout.findViewById(R.id.layout_titlebar);
        final View rlDebug = layout.findViewById(R.id.rl_debug);
        TextView showVersion = (TextView) layout.findViewById(R.id.app_version);
        showVersion.setText("：" + AppUtils.getVersionName(getContext()) + ":" + AppUtils.getVersionCode(getContext()));
        rlDebug.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setClass(getContext(), DebugActivity.class);
                startActivity(intent);
            }
        });
        rl1.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                if (rlDebug.getVisibility() != View.VISIBLE) {
                    rlDebug.setVisibility(View.VISIBLE);
                }
                return true;
            }
        });
        layout.findViewById(R.id.rl_change_nickname).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
//                intent.setClass(getApplication(), ChangeNicknameActivity.class);
                intent.setClass(getContext(), ChangeNicknameMvpActivity.class);
                startActivity(intent);
            }
        });

        layout.findViewById(R.id.layout_setting).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setClass(getContext(), SettingActivity.class);
                startActivity(intent);
            }
        });
        layout.findViewById(R.id.layout_walkiechannel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setClass(getContext(), WalkieChannelMvpActivity.class);
                startActivity(intent);
            }
        });
        layout.findViewById(R.id.rl_exit).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //退出同时选择是否自动登录
                showExitDialog();
            }
        });


        mTvNickName = (TextView) layout.findViewById(R.id.tv_nickname);
        EventBusAccountBean eventBusAccountBean = new EventBusAccountBean();
        eventBusAccountBean.setCurrentEvent(EventBusAccountBean.EVENT_CHANGE_NICKNAME);
        eventBusAccountBean.setTarget(this.getClass(), GroupsPresenterImpl.class, "onEventBusRequestAccount");
        EventBus.getDefault().post(eventBusAccountBean);
        builder.setView(layout);
        final AlertDialog dialog = builder.create();
        dialog.show();
    }

    private void showExitDialog() {
        /* @setIcon 设置对话框图标
         * @setTitle 设置对话框标题
         * @setMessage 设置对话框消息提示
         * setXXX方法返回Dialog对象，因此可以链式设置属性
         */
        final AlertDialog.Builder normalDialog = new AlertDialog.Builder(getActivity());
        normalDialog.setMessage("下次自动登录");
        normalDialog.setPositiveButton("是",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        SPUtil.put(getContext(), SPUtil.SPKeyGlobal.KEY_AUTOLOGIN, true);
                        SPUtil.put(getContext(), SPUtil.SPKeyGlobal.KEY_REMEMBER_PWD, true);
                        mExitHandler.sendMessageDelayed(new Message(), 500);
                    }
                });
        normalDialog.setNegativeButton("否",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //...To-do
                        SPUtil.put(getContext(), SPUtil.SPKeyGlobal.KEY_AUTOLOGIN, false);
                        mExitHandler.sendMessageDelayed(new Message(), 500);
                    }
                });
        // 显示
        normalDialog.show();
    }


    private Handler mExitHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            EventBusRemoteBean bean = new EventBusRemoteBean();
            bean.setCurrentEvent(EventBusRemoteBean.EVENT_UNBINDREMOTE);
            bean.setTarget(this.getClass(), RchatClientService.class, "onEventBusDispatchRemote");
            EventBus.getDefault().post(bean);
            PocAccount.getPocAccountInstance(getContext()).logout();
//            PocApplication.mWifiLocKManager.releaseWifiLock();
            getContext().stopService(new Intent(getContext(), PocService.class));
            //退出友盟
            MobclickAgent.onProfileSignOff();
            System.exit(0);

        }
    };
}
